package com.wq.sofa.framework.bolt;

import com.alipay.remoting.Connection;
import com.alipay.remoting.ConnectionEventProcessor;
import com.alipay.sofa.common.profile.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: wangqiang20995
 * @Date:2018/9/19
 * @Description:
 * @Resource:
 */
public class ConnectEventProcessor implements ConnectionEventProcessor {
    private AtomicBoolean connected = new AtomicBoolean();
    private AtomicInteger connectTimes = new AtomicInteger();
    private String remoteAddress;
    private Connection connection;
    private CountDownLatch countDownLatch;

    private Logger logger = LoggerFactory.getLogger(getClass());

    public ConnectEventProcessor(){
        countDownLatch = new CountDownLatch(1);
    }

    public boolean isConnected() throws InterruptedException {
        this.countDownLatch.await();
        return this.connected.get();
    }

    public int getConnectionTimes() throws InterruptedException {
        this.countDownLatch.await();
        return this.connectTimes.get();
    }

    public Connection getConnection() throws InterruptedException {
        this.countDownLatch.await();
        return this.connection;
    }

    public String getRemoteAddress() throws InterruptedException {
        this.countDownLatch.await();
        return this.remoteAddress;
    }

    public void reset(){
        this.connected.set(false);
        this.connectTimes.set(0);
        this.connection = null;
    }
    @Override
    public void onEvent(String remoteAddress, Connection connection) {
        if(StringUtil.isEmpty(remoteAddress)){
            throw new RuntimeException("远程连接地址不能为空");
        }

        this.remoteAddress = remoteAddress;
        this.connection = connection;
        logger.info("create a connection to remote address -->[{}]",remoteAddress);
        //onEvent方法必须先于其他方法之前被调用，否则无法将Connection双工通道赋值给类中的成员变量
        this.countDownLatch.countDown();
    }
}
